package cn.dansj.common.utils.spring.context;

import cn.dansj.common.processor.meta.WriteToResource;
import cn.dansj.common.utils.json.JSONUtils;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Order(Ordered.HIGHEST_PRECEDENCE)
@WriteToResource
public class PropertiesPropertySourceLoader implements PropertySourceLoader {
    public String[] getFileExtensions() {
        return new String[]{"properties", "xml"};
    }

    @Override
    public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
        Map<String, ?> properties = this.loadUseUtf8(resource);
        if (properties.isEmpty()) return Collections.emptyList();
        return Collections.singletonList(new OriginTrackedMapPropertySource(name, Collections.unmodifiableMap((Map<?, ?>) properties), true));
    }

    private Map<String, ?> loadUseUtf8(Resource resource) throws IOException {
        Properties props = new Properties();
        try (InputStream is = resource.getInputStream()) {
            String filename = resource.getFilename();
            if (filename != null && filename.endsWith(".xml")) {
                props.loadFromXML(is);
            } else {
                props.load(new InputStreamReader(is, StandardCharsets.UTF_8));
            }
        }
        return JSONUtils.toJSONObject(props);
    }
}
